package com.zhj.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.kafka.annotation.KafkaHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.TopicPartition;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Optional;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class KafkaConsumer {

    @KafkaListener(
        groupId = "test-2",
        topicPartitions = {
            @TopicPartition(topic = "test",partitions = {"0"})
        }
    )
    public void topicTest(ConsumerRecord<?,?> record, Acknowledgment acknowledgment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic){
        long offset = record.offset();
        System.out.println("消费者接收到消息："+ offset);
        Optional<?> message = Optional.ofNullable(record.value());
        if (message.isPresent()){
            Object msg = message.get();
            log.info("消费者消费了：topic"+topic+",message:"+msg);
            //手动确认
            acknowledgment.acknowledge();
        }
    }


}
